window.addEventListener(
  'message',
  function (event) {
    // We only accept messages from ourselves
    // if (event.source != window) return
    if (event.data.type && event.data.type == 'FROM_PAGE') {
      console.log('Content script received: ' + event.data.text)
      chrome.runtime.sendMessage(event.data.text)
    }
  },
  false
)

// 监听长连接
chrome.runtime.onConnect.addListener(function (port) {
  if (port.name == 'test-connect') {
    port.onMessage.addListener(function (msg) {
      console.log('收到长连接消息：', msg)
      if (msg.question == '你是谁啊？')
        port.postMessage({ answer: '我是你爸！' })
    })
  }
})

var myRequest = new Request('http://httpbin.org/post', {
  method: 'POST',
  body: JSON.stringify({ age: 18, name: 'LiHua' }),
})
function testFetch() {
  // fetch don't allow you to use a request twice, at least at current version
  // Using clone
  fetch(myRequest.clone())
    .then((response) => response.json())
    .then((response) => {
      console.dir(response)
    })
    .catch((error) => console.error(error))
}


let timer
let duration = Math.ceil((Math.random() * 2 + 5) * 1000 * 60)
function actionNote(kpointNos, kName) {
  console.log(`开始计时提交笔记，间隔时间：${duration / 1000}s`)
  timer = setInterval(() => {
    fetch('http://wljy.whut.edu.cn/edu/courseNote/saveCourseNote.ajax', {
      method: 'POST',
      mode: 'cors',
      body: JSON.stringify({
        kpointNos,
        content: `学习${kName}`,
        userId: '191493412300002',
      }),
    })
      .then((response) => {
        if (response.ok) {
          return response.json()
        } else {
          throw new Error('Something went wrong on api server!')
        }
      })
      .then((response) => {
        console.log('response', response)
        // ...
      })
      .catch((error) => {
        console.error(error)
      })
  }, duration)

  actionPlay()
}

/**
 * @desc 修改学习记录
 */
function modifyStudyHistory(query) {
  let duration = getVideoDuration()
  console.log('提交学习历史，end')
  let formdata = new FormData()
  let postData = {
    userId: 191493412300002,
    courseNo: query.courseNo,
    courlibNo: query.courlibNo,
    kPointNo: query.kpointNo,
    process: duration,
    type: 1,
  }
  for (let k in postData) {
    formdata.append(k, postData[k])
  }
  fetch('http://wljy.whut.edu.cn/edu/course/savePlayHistory.ajax', {
    method: 'POST',
    mode: 'cors',
    body: formdata,
  })
    .then((response) => {
      if (response.ok) {
        return response.json()
      } else {
        throw new Error('插入视频历史记录失败')
      }
    })
    .catch((error) => {
      console.error(error)
    })
}

/**
 * @desc 取消轮询刷课请求
 */
function canclePostAction() {
  clearInterval(timer)
  console.log('取消提交')
}

/**
 * @desc 播放视频
 */
function actionPlay() {
  let video = document.querySelector('video')
  if (video) {
    if (video.paused) {
      video.play()
    }
    video.onended = (event) => {
      console.log(
        'Video stopped either because 1) it was over, ' +
          'or 2) no further data is available.'
      )
      canclePostAction()
    }
  }
}

/**
 * @desc 获取视频时长
 */
function getVideoDuration() {
  try {
    let video = document.querySelector('video')
    return video.duration
  } catch (error) {

  }
}
